import os
import random
import shutil

def copy_random_images(dest_dir, txt_file, num_images):
    # 读取txt文件中的所有图片路径
    with open(txt_file, 'r') as f:
        image_paths = f.read().splitlines()

    # 筛选出jpg图片
    jpg_image_paths = [path for path in image_paths if path.lower().endswith('.jpg')]

    # 如果要复制的图片数量小于等于0或者大于可用的jpg图片数量，退出
    if num_images <= 0 or num_images > len(jpg_image_paths):
        print("Invalid number of images to copy.")
        return

    # 随机选择num_images张图片
    selected_images = random.sample(jpg_image_paths, num_images)

    # 复制选定的图片到目标文件夹
    for image_path in selected_images:
        image_name = os.path.basename(image_path)
        dest_path = os.path.join(dest_dir, image_name)
        shutil.copy(image_path, dest_path)
        print(f"Copying {image_name} to {dest_dir}")

if __name__ == "__main__":
    source_txt = 'gt_guiji_202308.txt'  # 包含所有图片路径的txt文件路径
    destination_folder = 'jpg_100'  # 目标文件夹路径
    num_images_to_copy = 100  # 要复制的图片数量

    # 创建目标文件夹
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    copy_random_images(destination_folder, source_txt, num_images_to_copy)
